﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using Jayrock.Json;
using Jayrock.Json.Conversion;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using System.IO;
using System.Net;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Qik
{
    public class QikService
    {
        private const string ENGINE_URL = "http://engine.qik.com/api/jsonrpc?apikey={0}";
        
        private QikConfig _config;

        public QikService(string config)
        {
            _config = config.DeserializeJsonTo<QikConfig>();
        }

        public List<QikVideo> GetVideos()
        {
            var result = new List<QikVideo>();
            var jsonArr = Invoke(ENGINE_URL, "qik.stream.public_user_streams", _config.Username) as JsonArray;
            if (jsonArr != null)
            {
                for (var i = 0; i < jsonArr.Length; i++)
                {
                    result.Add(((JsonObject)jsonArr[i]).ToQikVideo());
                }
            }
            return result;
        }

        public QikVideo GetVideo(int videoId)
        {
            var jsonObj = Invoke(ENGINE_URL, "qik.stream.public_info", videoId) as JsonObject;
            return jsonObj == null ? null : jsonObj.ToQikVideo();
        }

        #region Helper Methods

        protected object Invoke(string urlFormat, string method, params object[] args)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(string.Format(urlFormat, _config.ApiKey));
            webRequest.Method = "POST";

            using (Stream stream = webRequest.GetRequestStream())
            using (StreamWriter writer = new StreamWriter(stream))
            {
                JsonObject request = new JsonObject();
                request["id"] = 0;
                request["method"] = method;
                request["params"] = args;
                request.Export(new JsonTextWriter(writer));
            }

            using (WebResponse webResponse = webRequest.GetResponse())
            using (Stream stream = webResponse.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                var importContext = new ImportContext();
                var responseObj = importContext.Import(new JsonTextReader(reader));

                if (responseObj is JsonArray && ((JsonArray)responseObj).Length == 1)
                    return ((JsonArray)responseObj)[0];

                if (responseObj is JsonObject && ((JsonObject)responseObj)["fault"] != null)
                    throw new Exception(((JsonObject)responseObj)["faultString"] as string);

                throw new Exception("Unknown response object: " + responseObj.ToString());
            }
        }

        #endregion
    }

    #region Model
	
    public class QikVideo
    {
        public int Id { get; set; }
        public int UserId { get; set; }
        public string Title { get; set; }
        public string Url { get; set; }
        public string LargeThumbnailUrl { get; set; }
        public string SmallThumbnailUrl { get; set; }
        public string Filename { get; set; }
        public int Duration { get; set; }
        public int Views { get; set; }
        public string DeviceInfo { get; set; }
        public bool IsLive { get; set; }
        public List<string> Features { get; set; }
        public DateTime CreatedAt { get; set; }
        public string Country { get; set; }
        public string City { get; set; }
        public QikLocation Location { get; set; }
        public string EmbedCode { get; set; }
    }

    public class QikLocation
    {
        public decimal Lattitude { get; set; }
        public decimal Longitude { get; set; }
    }

	#endregion
}